package com.deer.wms.base.system.web.zhBusiness.work;

import com.deer.wms.base.system.model.bill.*;
import com.deer.wms.base.system.model.box.BoxItem;
import com.deer.wms.base.system.model.box.BoxItemDto;
import com.deer.wms.base.system.model.check.BoxItemCheck;
import com.deer.wms.base.system.model.check.BoxItemCheckDetail;
import com.deer.wms.base.system.model.task.RequestRepertory;
import com.deer.wms.base.system.model.task.RequestWcsRedis;
import com.deer.wms.base.system.model.task.TaskInfo;
import com.deer.wms.base.system.model.task.TaskInfoDto;
import com.deer.wms.base.system.model.ware.CellInfo;
import com.deer.wms.base.system.model.ware.CellInfoDto;
import com.deer.wms.base.system.model.zh.WorkTasks;
import com.deer.wms.base.system.service.bill.IBillOutMasterService;
import com.deer.wms.base.system.service.box.IBoxItemService;
import com.deer.wms.base.system.service.check.BoxItemCheckService;
import com.deer.wms.base.system.service.zh.WorkTasksService;
import com.deer.wms.base.system.util.JedisServiceUtil;
import com.deer.wms.common.core.result.CommonCode;
import com.deer.wms.common.core.result.Result;
import com.deer.wms.common.core.result.ResultGenerator;
import com.deer.wms.framework.util.ShiroUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**出库工作任务*/
@RestController
@RequestMapping("/billOutTasks")
@Slf4j
public class BillOutTasksController {
    @Autowired //工作任务
    private WorkTasksService workTasksService;
    @Autowired //出库单
    private IBillOutMasterService billOutMasterService;
    @Autowired //库存
    private IBoxItemService iBoxItemService;
    @Autowired //redis工具
    private JedisServiceUtil jedisServiceUtil;
    @Autowired //盘点
    private BoxItemCheckService boxItemCheckService;

    /*创建出库任务*/
    @PostMapping("/allocationTask")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result allocationCell(@RequestBody InserData inserData){
        String createUserName = ShiroUtils.getLoginName();
        List<WorkTasks> workTaskList = inserData.getWorkTaskList();

        for (WorkTasks workTasks : workTaskList) {
            Float esWeight = 0f; //已出库
            workTasks.setType(2) //出库
                    .setState(1) //已下发
                    .setCreateUserName(createUserName);//操作人
            /*货位查询*/
            List<CellInfoDto> cellCode= workTasksService.selectCellCodeFromByitemCode(workTasks);
            if(cellCode.isEmpty()){
                return ResultGenerator.genFailResult(CommonCode.STOCK_NOT_ENOUGH);
            }
            float Weight = workTasks.getWeight(); //预出库
            SimpleDateFormat date = new SimpleDateFormat("yyyyMMdd-HHmmss");
            /*货位分配*/
            for (CellInfoDto cellInfoDto : cellCode) {
                TaskInfoDto taskInfoDto = new TaskInfoDto();
                taskInfoDto.setCellCode(cellInfoDto.getCellCode())//货位
                        .setTaskStartTime(date.format(new Date()))
                        .setState(1)
                        .setType(1);
                esWeight = esWeight + cellInfoDto.getWeight();

                //明细改为出库中
                billOutMasterService.updateBillOutDetailStateById(workTasks.getBillOutDetailId());
                //出库单改为部分出库,如果全部出库,则出库单"出库完毕"
                int billOutSum = billOutMasterService.findBillOutOver(workTasks.getBillOutPlanId());//查询是否全部完成
                if(billOutSum != 0){
                    //部分出库
                    billOutMasterService.updateBillOutPlanState2(workTasks.getBillOutPlanId());
                }else {
                    //出库完毕
                    billOutMasterService.updateBillOutPlanState3(workTasks.getBillOutPlanId());
                }
                //根据计划id和物料名称查sap明细id

                int sapId = billOutMasterService.findSapIdByPlanId(workTasks);
                //添加SAP明细重量
                BillOutSapDetail billOutSapDetail = new BillOutSapDetail();
                billOutSapDetail.setBillOutSapDetailId(sapId)//id
                        .setWeight(cellInfoDto.getWeight());//已出数量
                billOutMasterService.updateSapWright(billOutSapDetail);

                //判断如果sap已出大于预收,则完成
                BillOutSapDetail detailWeight = billOutMasterService.findDetailWeight(sapId);
                if(detailWeight.getERFMG_RECEIVED() >= detailWeight.getERFMG()){
                    detailWeight.setState(3);
                    billOutMasterService.updateSapDetailState(detailWeight);
                }else {
                    detailWeight.setState(2);
                    billOutMasterService.updateSapDetailState(detailWeight);
                }
                //如果所有明细完成,则出库计划完成(master)
                //查询sapId
                int id = billOutMasterService.findSapIdByDetailId(sapId);
                int planSum = billOutMasterService.sumPlan(id);
                if(planSum == 0){
                    //如果sap明细全部完成,则计划单完成
                    billOutMasterService.updatePlan(id);
                }
                int outType  = billOutMasterService.findBillOutType(id);
                //更新工作任务
                taskInfoDto.setId(cellInfoDto.getTaskId())
                        .setOutType(outType)//出库类型
                        .setCreateUserName(createUserName)//创建人
                        .setCurrentDevice(workTasks.getDeviceName())//机台名称
                        .setStartPosition("立体库")
                        .setEndPosition("立体库");
                workTasksService.updateWorkTasksById(taskInfoDto);

                //添加出库流水
                BillOutDetailDevice detailDevice = new BillOutDetailDevice();
                detailDevice.setBoxId(cellInfoDto.getBoxId()) //托id
                        .setPlanNo(workTasks.getPlanNo())
                        .setPlanId(workTasks.getPlanId())
                        .setDeviceName(workTasks.getDeviceName())
                        .setMemo(cellInfoDto.getMemo())
                        .setCreateName(createUserName)
                        .setBillInDetailId(cellInfoDto.getBillInDetailId());//明细id
                billOutMasterService.insertBillOutDetailDevice(detailDevice);
                //redis添加任务
                RequestWcsRedis requestWcsRedis = new RequestWcsRedis();
                requestWcsRedis.setLocation(cellInfoDto.getCellCode())//库位
                        .setType(1)
                        .setAimlocation(" ");//任务类型
                jedisServiceUtil.leftPush("YL:BillOut", requestWcsRedis);
                //托盘出库中
                iBoxItemService.outBoxItem(cellInfoDto.getId());
                if (esWeight >= Weight) {
                    break;
                }
            }
        }

        return ResultGenerator.genFailResult(CommonCode.WS_SUCCESS);
    }

    /*收到出库成功信息,更改任务作业状态,添加任务号*/
    @PostMapping("/sendTaskResult")
    @ResponseBody
    @Transactional
    public Result sendTaskResult(@RequestBody RequestRepertory requestRepertory){
        WorkTasks workTasks = new WorkTasks();
        workTasks.setTaskNumber(requestRepertory.getTaskNumber());
        //查询任务的货位
        CellInfoDto cellInfo = workTasksService.findCellIdByTaskNumber(workTasks.getTaskNumber());
        //库位变成 0-空闲
        workTasksService.updateCell(cellInfo.getCellId());

        /*生产出库在途/试做品出库在途 其他直接删*/
        //查询出库类型和托盘号
        TaskInfo boxType = workTasksService.findOutType(requestRepertory.getTaskNumber());
        //查询托盘号
        //2退货出库
        if(boxType.getOutType() == 2){
            //删除托盘
            workTasksService.delByBoxCode(boxType.getBoxCode());
            TaskInfo taskInfo = workTasksService.selectWorkTask(requestRepertory.getTaskNumber());
            workTasksService.deleteWorkTask(taskInfo);
            workTasksService.insertWorkTaskOld(taskInfo);
            return  ResultGenerator.genBillSuccessResult(null,workTasks.getTaskNumber(),"成功,退货出库完成");
        }
        //生产和试做品前往机台
      workTasks.setState(9);
        //改变库存状态(立库→在途)
        workTasksService.updateStateByBoxCode(workTasks);
        return  ResultGenerator.genBillSuccessResult(null,workTasks.getTaskNumber(),"成功,前往线边仓");

    }

    /*手持机出立体库,入线边仓*/
    @PostMapping("/inEdgeBox")
    @ResponseBody
    @Transactional
    public Result inEdgeBox(String json){
        List<WorkTasks> workTaskList = new Gson().fromJson(json, new TypeToken<List<WorkTasks>>(){}.getType());
        String boxMsg = workTaskList.get(0).getMsg();
        String[] batchMsg = boxMsg.split(",");
        WorkTasks workTask = new WorkTasks();
        workTask.setState(4)
                .setBatch(batchMsg[4]); //流水批号
        //根据条码找到对应任务号
        Long taskNumber = workTasksService.findTaskNumberByBatch(workTask.getBatch()).get(0);
        workTask.setTaskNumber(taskNumber);
        //改变库存状态(在途→线边仓)
        workTasksService.updateStateByBoxCode(workTask);
        //立体库删除 线边仓加
        BoxItemDto boxItem = workTasksService.selectBoxMSGByTaskNumber(workTask.getTaskNumber());
        iBoxItemService.deleteBoxItemById(boxItem.getId());
        iBoxItemService.insertBoxItemEdge(boxItem);
        //任务作业到历史记录
        TaskInfo taskInfo = workTasksService.selectWorkTask(workTask.getTaskNumber());
        workTasksService.deleteWorkTask(taskInfo);
        workTasksService.insertWorkTaskOld(taskInfo);

        return ResultGenerator.genFailResult(CommonCode.WS_SUCCESS);
    }

    /*线边仓出库*/
    @PostMapping("/updateEdgeBoxByBatch")
    @ResponseBody
    @Transactional
    public Result updateEdgeBoxByBatch(String json){
        List<WorkTasks> workTaskList = new Gson().fromJson(json, new TypeToken<List<WorkTasks>>(){}.getType());

        for (WorkTasks workTask : workTaskList) {
            String boxMsg = workTask.getMsg();
            String[] msg = boxMsg.split(",");
            Float msg3 = Float.parseFloat(msg[3].replaceAll("[a-zA-Z]", ""));
            workTask.setItemCode(msg[1]) //物料号
                    .setItemName(msg[2]) //物料描述
                    .setWeight(msg3) //重量
                    .setBatch(msg[4]); //唯一批号
            int sum = iBoxItemService.findEdgeSumByBatch(workTask);
            if(sum == 0){
                return ResultGenerator.genFailResult(CommonCode.BOXEDGE_ERROR);
            }
            //减少线边仓库存
            iBoxItemService.updateBoxItemEdgeByBatch(workTask);
            Float weight = iBoxItemService.findBoxItemEdgeByBatch(workTask);
            if(weight <= 0){
                //删除线边仓重量为0的原料
                iBoxItemService.delBoxItem(workTask);
            }
        }

        return ResultGenerator.genSuccessResult();
    }


    /*开始盘点任务*/
    @PostMapping("/checkTaskWork")
    @ResponseBody
    @Transactional
    public Result checkTaskWork(String json) {
        //查询如果有未盘点完成的单据,则不能开始
        int sum = boxItemCheckService.findCheckState();
        if(sum != 0){
            return ResultGenerator.genFailResult(CommonCode.CHECKSTATE_ERROR);
        }
        //改变盘点单状态2盘点中
        int id = Integer.parseInt(json);
        boxItemCheckService.updateCheckDetailGo(id);
        //根据id查询所有库位
        List<BoxItemCheckDetail> checkDetailList= boxItemCheckService.findCheckDetailListById(id);
        //库位存到redis中
        RequestWcsRedis requestWcsRedis = new RequestWcsRedis();
        for (BoxItemCheckDetail boxItemCheckDetail : checkDetailList) {
            String cellCode = boxItemCheckDetail.getCellCode();
            requestWcsRedis.setLocation(cellCode)//库位
                    .setType(2)//盘库
                    .setAimlocation(" ");//任务类型
            jedisServiceUtil.leftPush("YL:BillOut", requestWcsRedis);
        }
        boxItemCheckService.updateCheckDetailGo(id);
        return ResultGenerator.genFailResult(CommonCode.WS_SUCCESS);
    }


}
